package main

import (
	"flag"
	"fmt"
	"log"

	"github.com/albenik/go-serial/v2/enumerator"
	"github.com/crackcomm/go-clitable"
)

var (
	list, help, cli bool
)

func init() {
	flag.BoolVar(&cli, "c", false, "config serial in cli mode")
	flag.BoolVar(&list, "l", true, "list ports")
	flag.BoolVar(&help, "h", false, "help")
}

func listPort() []*enumerator.PortDetails {
	ports, err := enumerator.GetDetailedPortsList()
	if err != nil {
		log.Fatal(err)
	}
	if len(ports) == 0 {
		log.Fatal("No serial ports found!")
	}

	table := clitable.New([]string{"Idx", "Name", "ID", "MFG", "Desc"})
	var idxCnt uint32 = 0
	for _, port := range ports {
		table.AddRow(map[string]interface{}{"Idx": idxCnt, "Name": port.Name, "ID": port.VID + ":" + port.PID, "MFG": port.Manufacturer, "Desc": port.Product})
		idxCnt++
	}

	table.Markdown = true
	table.Print()

	return ports
}

func startSerial(portName string, baudrate uint32) {

}

func main() {
	var portIdx, baudrate uint32 = 0, 115200
	var ports []*enumerator.PortDetails

	flag.Parse()
	if help {
		flag.Usage()
		return
	}
	if cli {
		ports = listPort()
		numPorts := len(ports)
		if numPorts <= 0 {
			fmt.Printf("No serial port found.")
			return
		}
		for {
			fmt.Printf("Select a serial port:(0-%d)[0] ", numPorts-1)
			fmt.Scanln(&portIdx)
			if portIdx < uint32(numPorts) {
				break
			}
		}
		fmt.Printf("Input baudrate:[115200] ")
		fmt.Scanln(&baudrate)
		startSerial(ports[portIdx].Name, baudrate)
		return
	}
	if list {
		listPort()
		return
	}
}
